/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cageballcommon.io.impl;

import cageballcommon.exceptions.CageballIOException;
import cageballcommon.io.interfaces.CageballWriter;
import cageballcommon.messages.Action;
import cageballcommon.messages.InitTeam;
import cageballcommon.messages.State;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;

/**
 *
 * @author kanonas
 */
public class CageballFileWriter implements CageballWriter {

    private File file;
    private PrintStream out;
    private Gson gson;

    public CageballFileWriter(File file) throws IOException {

        this.file = file;

        if (!file.exists()) {
            file.createNewFile();
        }

        out = new PrintStream(new FileOutputStream(file));

        gson = new Gson();
    }

    public void writeState(State state) throws CageballIOException {
        write(state);
    }

    public void writeAction(Action action) throws CageballIOException {
        write(action);
    }

    public void writeInitTeam(InitTeam initTeam) throws CageballIOException {
        write(initTeam);
    }

    public void writeProperties(Properties properties) throws CageballIOException {
        write(properties);
    }

    public void close() throws CageballIOException {
        out.close();
    }

    private void write(Object o) throws CageballIOException{
        out.println(gson.toJson(o));
        if(out.checkError()){
            throw new CageballIOException("Error writing to file");
        }
    }
}
